package com.smssalama.gui;

import java.util.Vector;

import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import com.smssalama.AlertManager;
import com.smssalama.SMSSalama;
import com.smssalama.SMSSalamaSession;
import com.smssalama.i18n.CommandLabels;
import com.smssalama.i18n.Labels;
import com.smssalama.i18n.ScreenTitles;
import com.smssalama.storage.contact.Contact;
import com.smssalama.storage.framework.ObjectListener;
import com.smssalama.storage.framework.ObjectStore;
import com.smssalama.storage.framework.StorableComparatorImpl;
import com.smssalama.storage.framework.ObjectStore.ObjectEnumeration;

/**
 * Displays a list of all contacts.
 * 
 * @author Arnold P. Minde
 *
 */
public class Contacts extends List implements CommandListener, ObjectListener {
	private Labels LABELS = Labels.labels();
	private CommandLabels CMD_LABELS = CommandLabels.cmdLabels();

	Vector contactIds = new Vector();
	
	Command exitCmd = new Command(CMD_LABELS.exit(),
			CMD_LABELS.exitLong(), Command.EXIT, 3);
	Command backCmd = new Command(CMD_LABELS.back(), Command.BACK,
			1);
	Command viewCmd = new Command(CMD_LABELS.view(), Command.ITEM,
			1);
	Command editCmd = new Command(CMD_LABELS.edit(), Command.ITEM,
			2);
	Command newCmd = new Command(CMD_LABELS.NEW(), Command.ITEM, 2);
	Command deleteCmd = new Command(CMD_LABELS.delete(),
			Command.ITEM, 2);

	public Contacts() {
		super(ScreenTitles.screenTitles().contacts(), Choice.IMPLICIT);
		this.addCommand(this.exitCmd);
		this.addCommand(this.backCmd);
		this.addCommand(this.viewCmd);
		this.addCommand(this.editCmd);
		this.addCommand(this.newCmd);
		this.addCommand(this.deleteCmd);
		this.setSelectCommand(this.viewCmd);
		this.setCommandListener(this);
		reloadContacts();
	}

	public synchronized void reloadContacts() {
		try {
			//Store selected index
			int selectedIndex = getSelectedIndex();
			int selectedContactId = getSelectedContactId();

			ObjectStore contactsStore = SMSSalamaSession.getSession()
					.getUserSettings().getContactsStore();
			//contactsStore.removeStorageListener(this.storageListener);
			contactsStore.removeObjectListener(this);
			ObjectEnumeration enumeration = contactsStore.search(null,
					new StorableComparatorImpl(
							new Object[] { Contact.COMPARE_CONTACT_NAME }));
			this.contactIds.removeAllElements();
			this.deleteAll();
			while (enumeration.hasNextObject()) {
				Contact c = (Contact) enumeration.nextObject();
				this.contactIds.addElement(new Integer(c.getRecordId()));
				this.append(c.getContactName(), null);
			}
			enumeration.close();
			//contactsStore.addStorageListener(this.storageListener);
			contactsStore.addObjectListener(this);
			
			//Attempt to restore the selected index as it were before
			if (Contacts.this.contactIds.indexOf(new Integer(selectedContactId)) >= 0) {
				setSelectedIndex(Contacts.this.contactIds.indexOf(new Integer(
						selectedContactId)), true);
			} else if (selectedIndex - 1 >= 0) {
				setSelectedIndex(selectedIndex - 1, true);
			}
		} catch (Exception e) {
			e.printStackTrace();
			append("Error: " + e.getMessage(), null);
		}
	}

	public synchronized int getSelectedContactId() {
		if (this.getSelectedIndex() >= 0) {
			int contactId = ((Integer) this.contactIds.elementAt(this
					.getSelectedIndex())).intValue();
			return contactId;
		} else {
			return -1;
		}
	}
	
	public synchronized void reloadContact(int contactId){
		int index = contactIds.indexOf(new Integer(contactId));
		if(index>0){
			Contact contact;
			try {
				contact = (Contact)SMSSalamaSession.getSession()
				.getUserSettings().getContactsStore().getStorable(contactId);
			} catch (Exception e) {
				e.printStackTrace();
				return;
			}
			if(contact!=null){
				contactIds.setElementAt(contact, index);
				this.set(index, contact.getContactName(), null);
			}
		}
	}

	public synchronized void commandAction(Command command, Displayable displayable) {
		if (command == this.exitCmd) {
			SMSSalama.quitApp();
		} else if (command == this.backCmd) {
			AlertManager.showDisplayable(Home.getHomeScreen());
		} else if (command == this.newCmd) {
			ContactEditor editor = new ContactEditor(this);
			AlertManager.showDisplayable(editor);
		} else if (command == this.viewCmd) {
			int contactId = getSelectedContactId();
			if (contactId == -1) {
				return;
			}
			try {
				Contact contact = (Contact) SMSSalamaSession.getSession()
						.getUserSettings().getContactsStore().getStorable(
								contactId);
				ContactViewer viewer = new ContactViewer(contact, this);
				AlertManager.showDisplayable(viewer);
			} catch (Exception e) {
				e.printStackTrace();
				AlertManager.showError(this, e);
			}
		} else if (command == this.editCmd) {
			try {
				int contactId = getSelectedContactId();
				if (contactId > 0) {
					Contact contact = (Contact) SMSSalamaSession.getSession()
							.getUserSettings().getContactsStore().getStorable(
									contactId);
					ContactEditor editor = new ContactEditor(this, contact);
					AlertManager.showDisplayable(editor);
				}
			} catch (Exception e) {
				e.printStackTrace();
				AlertManager.showError(this, e);
			}
		} else if (command == this.deleteCmd) {
			int contactId = getSelectedContactId();
			if (contactId == -1) {
				return;
			}
			try {
				SMSSalamaSession.getSession().getUserSettings()
						.getContactsStore().deleteStorable(contactId);
			} catch (Exception e) {
				e.printStackTrace();
				AlertManager.showError(this, e);
			}
		}
	}

	public synchronized void objectAdded(ObjectStore store, int recordId) {
		reloadContacts();
	}

	public synchronized void objectChanged(ObjectStore store, int recordId) {
		reloadContact(recordId);
	}

	public synchronized void objectDeleted(ObjectStore store, int recordId) {
		int index = contactIds.indexOf(new Integer(recordId));
		if(index>=0){
			contactIds.removeElementAt(index);
			Contacts.this.delete(index);
		}
	}
}
